package com.jnu.testdrivendevelopment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.jnu.testdrivendevelopment.data.Shop;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MapViewFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MapViewFragment extends Fragment {

    private MapView mMapView;
    private BaiduMap baiduMap;

    public MapViewFragment() {
        // Required empty public constructor
    }
    public static MapViewFragment newInstance(String param1, String param2) {
        MapViewFragment fragment = new MapViewFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_map_view,container);

        //地图初始化
        mMapView=rootView.findViewById(R.id.mapView);
        baiduMap = mMapView.getMap();
        LatLng centerPoint = new LatLng(22.2559,113.541112); //修改百度地图的初始位置
        MapStatus mMapStatus = new MapStatus.Builder().target(centerPoint).zoom(17).build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        baiduMap.setMapStatus(mMapStatusUpdate);

        //获取网络数据并根据数据添加标记点
        final ShopLoader shopLoader = new ShopLoader();
        Handler handler = new Handler(Looper.getMainLooper()) {
            public void handleMessage(Message msg) {
                drawShops(shopLoader.getShops());
            }
        };
        shopLoader.load(handler, "http://file.nidama.net/class/mobile_develop/data/bookstore.json");

        return rootView;
    }
    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    //封装添加标记点操作
    private void drawShops(ArrayList<Shop> shops){
        int index=0;

        for(;index<shops.size();index++){
            Shop shop=shops.get(index);
            //标记点名字
            String shopName=shop.getName();
            //标记点位置
            LatLng centerPoint=new LatLng(shop.getLatitude(),shop.getLongitude());
            //添加标记点
            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.shop_img);
            MarkerOptions markerOption = new MarkerOptions().icon(bitmap).position(centerPoint);
            Marker marker = (Marker) baiduMap.addOverlay(markerOption);
            //添加文字
            OverlayOptions textOption = new TextOptions().bgColor(0xAAFFFF00).fontSize(50).fontColor(0xFFFF00FF).text(shopName).rotate(0).position(centerPoint);
            baiduMap.addOverlay(textOption);
            //响应事件
            baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker arg0) {
                    Toast.makeText(getContext(), "Marker被点击了！", Toast.LENGTH_SHORT).show();
                    return false;
                }
            });
        }
    }

    //封装数据的获取和解析操作，定义一个成员可以直接获取解析以后的数据
    private class ShopLoader{
        public ArrayList<Shop> getShops() {
            return shops;
        }

        public void setShops(ArrayList<Shop> shops) {
            this.shops = shops;
        }

        private ArrayList<Shop> shops;
        public ShopLoader() {
            shops=new ArrayList<>();
        }

        public void load(final Handler handler, final String url) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String content = download(url);
                    parseJson(content);
                    handler.sendEmptyMessage(1);
                }
            }).start();
        }

        //JSON数据的解析
        private void parseJson(String content) {
            try {
                //这里的text就是上边获取到的数据，一个String.
                JSONObject jsonObject = new JSONObject(content);
                JSONArray jsonDatas = jsonObject.getJSONArray("shops");
                int length = jsonDatas.length();
                String test;
                for (int i = 0; i < length; i++) {
                    JSONObject shopJson = jsonDatas.getJSONObject(i);
                    Shop shop = new Shop();
                    shop.setName(shopJson.getString("name"));
                    shop.setLatitude(shopJson.getDouble("latitude"));
                    shop.setLongitude(shopJson.getDouble("longitude"));
                    shop.setMemo(shopJson.getString("memo"));
                    shops.add(shop);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //网络数据的获取
        public String download(final String url){
            try {
                URL urlID = new URL(url);
                HttpURLConnection conn = null;
                conn = (HttpURLConnection) urlID.openConnection();
                //设置连接属性。不喜欢的话直接默认也阔以
                conn.setConnectTimeout(5000);//设置超时
                conn.setUseCaches(false);
                conn.connect();
                //这里才真正获取到了数据
                InputStream inputStream = conn.getInputStream();
                InputStreamReader input = new InputStreamReader(inputStream);
                BufferedReader buffer = new BufferedReader(input);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    String inputLine;
                    StringBuffer resultData = new StringBuffer();
                    //StringBuffer字符串拼接很快
                    while ((inputLine = buffer.readLine()) != null) {
                        resultData.append(inputLine);
                    }
                    String text = resultData.toString();
                    Log.v("out---------------->", text);
                    return (text);
                }
                else return url;
            } catch (IOException ioException) {
                ioException.printStackTrace();
                return null;
            }
        }
    }
}